package prv.pursuivant.unimportant.scraps;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;

import prv.pursuivant.config.CategorySerializer;
import prv.pursuivant.config.impl.XStreamCategorySerializerModule;
import prv.pursuivant.core.AchievType;
import prv.pursuivant.core.AchievTypesTree;
import prv.pursuivant.core.impl.KindImpl;

import com.google.inject.Guice;
import com.google.inject.internal.Sets;

public class IconLeech {

	@SuppressWarnings("unused")
	private final String[] args;

	public IconLeech(String[] args) {
		this.args = args;
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		new IconLeech(args).run();
	}

	private void run() throws IOException {
		CategorySerializer serializer = Guice.createInjector(
				new XStreamCategorySerializerModule()).getInstance(
				CategorySerializer.class);
		AchievTypesTree tree = serializer.readTree(new FileInputStream(
				"runWD/config/category.168.xml"));
		Set<AchievType> toBeRead = Sets.newHashSet();
		AchievType root = tree.getRoot();
		fillSetToRead(root, tree, toBeRead);
		for (AchievType achiev : toBeRead) {
			URL achievUrl = new URL("http://wowhead.com/?achievement="
					+ achiev.getId() + "&power");
			byte[] read = readOnline(achievUrl);
			String icon = new String(read);
			try {
				icon = icon.substring(icon.indexOf("icon:"));
				icon = icon.substring(icon.indexOf("'") + 1);
				icon = icon.substring(0, icon.indexOf("'"));
				System.out.println(achiev.getName() + ": {" + icon + "}");
			} catch (RuntimeException e) {
				System.err.println("Achiev: " + achiev.getName());
				System.err.println("URL: " + achievUrl);
				System.err.println("value: " + read);
				System.err.println("error: " + icon);
				throw e;
			}
			URL iconUrl = new URL(
					"http://static.wowhead.com/images/icons/medium/"
							+ icon.toLowerCase() + ".jpg");
			byte[] iconData = readOnline(iconUrl);
			FileOutputStream fos = new FileOutputStream("runWD/icons/achiev."
					+ achiev.getId() + ".jpg");
			fos.write(iconData);
			fos.close();
		}
	}

	private void fillSetToRead(AchievType achiev, AchievTypesTree tree,
			Set<AchievType> toBeRead) {
		if (achiev.getKind() == KindImpl.META
				|| achiev.getKind() == KindImpl.NORMAL)
			toBeRead.add(achiev);
		for (String critId : achiev.getCriteria())
			fillSetToRead(tree.findAchievTypeById(critId), tree, toBeRead);
	}

	protected byte[] readOnline(URL url) throws IOException {
		System.out.println("Getting url " + url);
		IOException ioe = null;
		int tries = 20;
		while (tries > 0)
			try {
				byte[] result = singleTry(url);
				return result;
			} catch (IOException e) {
				System.out.println(e + ", tries left: " + (--tries));
				ioe = e;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					ioe = new IOException(e1);
				}
			}
		throw ioe;
	}

	protected byte[] singleTry(URL url) throws IOException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setAllowUserInteraction(false);
		connection.setUseCaches(false);
		connection.setRequestProperty("User-Agent",
				"Mozilla/5.0 Gecko/20070219 Firefox/2.0.0.2");
		connection.setDoOutput(false);
		connection.setConnectTimeout(2000);
		connection.setReadTimeout(2000);
		InputStream stream = connection.getInputStream();
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		try {
			byte[] buff = new byte[8192];
			int i = 0;
			while (0 < (i = stream.read(buff))) {
				result.write(buff, 0, i);
			}
		} catch (IOException e) {
			throw e;
		} catch (RuntimeException e) {
			throw e;
		} catch (Throwable e) {
			throw new IOException(e);
		} finally {
			stream.close();
			connection.disconnect();
		}
		return result.toByteArray();
	}

}
